import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from '@/views/Index.vue'
import Home from '@/views/home.vue'
import Detailed from '@/views/detailed.vue'
import Commodity from '@/views/commodity.vue'
import Favorite from '@/views/Favorite.vue'
import Orders from '@/views/orders.vue'
// import text from '../views/text.vue'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home/index'
  },
  {
    //首页导航栏和下面
    path: '/home',
    name: 'home',
    component: Home,
    children: [
      //子路由
      {
        //首页
        path: 'Index',
        name: 'Index',
        component: Index,
      },
      {
        //详细
        path: 'detailed/:id',
        name: 'detailed',
        component: Detailed,
      },
      //查看更多
      {
        path: 'commodity',
        name: 'Commodity',
        component: Commodity
      },
      //我的喜欢
      {
        path: 'favorite',
        name: 'Favorite',
        component: Favorite
      },
      //订单中心
      {
        path: 'orders',
        name: 'Orders',
        component: Orders
      }
    ]
  },

  //登录
  {
    path: '/Login',
    name: 'login',
    component: () => import('../views/login.vue')
  },
  //注册
  {
    path: '/Register',
    name: 'register',
    component: () => import('../views/register.vue')
  },
  {
    //购物车
    path: '/shopping',
    name: 'shopping',
    component: () => import('../views/shopping.vue')
  },
  {
    //结算页
    path: '/clearing',
    name: 'clearing',
    component: () => import('../views/clearing.vue')
  },
  {
    //成功页
    path: '/succeed',
    name: 'Succeed',
    component: () => import('../views/succeed.vue')
  },
  // 404找到不存在的页面显示404 ******
  {
    path: '*',
    component: () => import('../views/NotFound.vue')
  },
]
const router = new VueRouter({
  // mode: 'history',
  routes
})
//全局导航路由守卫
//用于存放要权限访问的页面
const authUrls = ['/clearing', '/succeed'];

router.beforeEach((to, from, next) => {
  if (!authUrls.includes(to.path)) {
    // 非权限页面，直接放行
    next();
  } else {
    // 权限页面，需要进行登录状态验证或其他权限验证逻辑
    const token = localStorage.getItem('token');
    if (token) {
      // 已登录，放行
      next();
    } else {
      // 未登录，跳转到登录页面，并记录跳转前的页面路径以便登录后跳转回来
      next('/login?redirect=' + encodeURIComponent(to.fullPath));
    }
  }
});

export default router
